<?php

namespace App\Service\OpenShop\Merchant;

use App\Enums\BaseErrorCode;
use App\Enums\OpenShop\InvestmentPromotion\MainProcessEnum;
use App\Enums\OpenShop\InvestmentPromotion\ShopManualEnum;
use App\Enums\OpenShop\InvestmentPromotion\SignOrderEnum;
use App\Enums\OpenShop\InvestmentPromotion\UserOrderEnum;
use App\Enums\OpenShop\MissionTemplateEnum;
use App\Exceptions\Custom\ResponseHttpException;
use App\Http\Resources\OpenShop\InvestmentPromotion\OrderDetailResource;
use App\Http\Resources\OpenShop\InvestmentPromotion\ProcessDetailResource;
use App\Http\Resources\OpenShop\ShopLocation\OrderPayHistoryResource;
use App\Library\Encrypt\Reversible;
use App\Models\OpenShop\InvestmentPromotion\OpenShopContractTemplateModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopLocationModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopMainProcessModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopProcessDetailModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSignOrderModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSignOrderPayHistoryModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSiteMissionModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopUserContractModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopUserExtContractModel;
use App\Models\OpenShop\Site\OpenShopMissionTemplateModel;
use App\Remote\Orm\OrmShopRemote;
use App\Service\OpenShop\Feishu\ShopManualService;
use App\Service\OpenShop\User\RmsUserService;
use App\Service\OpenShop\OrderService as OpenShopOrder;
use App\Service\OpenShop\Wap\SignOrderService;
use Exception;
use GuzzleHttp\Exception\GuzzleException;
use Kuafu\File\FileUtil;

class OrderService
{
    const RMS_GET_CODE_INFO = 'api/internal/openShop/getShopByCode';
    const ORM_GET_CODE_INFO = 'internal/getStoreByShopId';

    public static function detail($shopId, $brandId)
    {
        $model        = (new SignOrderService('',
            OpenShopSignOrderModel::getModelByShopId($shopId)))->getSignOrderInMerchant();
        $orderInfoRes = OpenShopOrder::detail($model->orderNo, 0, true);
        //获取门店
        $locationModel = OpenShopLocationModel::query()
                                              ->where('orderNo', $model->orderNo)
                                              ->first();
        $shopInfo      = [
            'shopCode'      => $model->shopCode ?? '-',
            'addressPrefix' => $locationModel->shopAddressPrefix ?? '-',
            'addressDetail' => $locationModel->shopDetailAddress ?? '-',
            'establishedAt' => isset($locationModel->createdAt) ? $locationModel->createdAt->toDateString() : '-',
        ];
        if (null != $locationModel) {
            if ($locationModel->confirmStatus == OpenShopLocationModel::SUBMIT_REPORT_STATUS_ON) {
                $shopInfo = [
                    'shopCode'      => $model->shopCode ?? '-',
                    'addressPrefix' => $locationModel->shopAddressPrefix,
                    'addressDetail' => $locationModel->shopDetailAddress,
                    'establishedAt' => $locationModel->createdAt->toDateString(),
                ];
            }
        }
        //订货
        $urlOrm      = config('orm.domain') . self::ORM_GET_CODE_INFO;
        $bodyOrm     = ['brandId' => $brandId, 'shopId' => $shopId];
        $headerOrm   = ['internal-key' => config('orm.internalKey'), 'internal-token' => config('orm.internalValue')];
        $responseOrm = getOrmMessageCommon("GET", $urlOrm, $bodyOrm, $headerOrm, 'query');
        return [
            'order'     => [
                'orderNo'       => $model->orderNo,
                'contractNo'    => 'KF' . ($model->shopCode ?? '-'),
                'proposer'      => optional($orderInfoRes['orderDetail']->identityCardRel)->name . ' | ' . (optional($orderInfoRes['orderDetail']->identityCardRel)->gender == 2 ? '男' : '女') . ' | ' . optional($orderInfoRes['orderDetail']->identityCardRel)->nativePlace,
                'phone'         => optional($orderInfoRes['orderDetail']->baseInfoRel)->mobile,
                'wechat'        => optional($orderInfoRes['orderDetail']->baseInfoRel)->weChatNumber,
                'addressPrefix' => optional($orderInfoRes['orderDetail']->baseInfoRel)->addressPrefix,
                'addressDetail' => optional($orderInfoRes['orderDetail']->baseInfoRel)->address,
                'postCode'      => optional($orderInfoRes['orderDetail']->baseInfoRel)->postCode,
            ],
            'shop'      => $shopInfo,
            'logistics' => [
                'name'          => $responseOrm['data']['contact_man'] ?? '-',
                'phone'         => $responseOrm['data']['phone'] ?? '-',
                'addressPrefix' => ($responseOrm['data']['province'] ?? '-') . ($responseOrm['data']['city'] ?? '-') . ($responseOrm['data']['county'] ?? '-'),
                'addressDetail' => $responseOrm['data']['address'] ?? '-',
            ],
        ];
    }

    //合同列表
    public static function contractList($shopId)
    {
//        $model = (new SignOrderService('',
//            OpenShopSignOrderModel::getModelByShopId($shopId)))->getSignOrderInMerchant();

        // 获取主单
        $mainProcess = OpenShopMainProcessModel::getMainOrder($shopId);
        if (null === $mainProcess) {
            return [];
        }

        $model = $mainProcess->signOrderRel;

        if (null === $model) {
            return [];
        }
        //获得合同编号
        $contractId = OpenShopUserContractModel::query()
                                               ->where('orderNo', $model->orderNo)
                                               ->where("contractStatus",
                                                   OpenShopUserContractModel::CONTRACT_STATUS_NORMAL)
                                               ->pluck('id');
        if ($model->step < UserOrderEnum::STEP_FINISH_CONTRACT) {
            $contractInfo = [];
        } else {
            $contractInfo = OpenShopUserExtContractModel::query()
                                                        ->whereIn('contractId', $contractId)
                                                        ->get()
                                                        ->map(function ($item) {
                                                            return [
                                                                'text' => $item->contractName,
                                                                'url'  => privateFilePath($item->downloadUrl),
                                                            ];
                                                        })->toArray();
        }
        //门店手册
        $tempList  = ShopManualService::getAllByOrderNo($model->orderNo)[0]['files'] ?? [];
        $datumList = [];
        foreach ($tempList as $item) {
            if ($item['type'] == ShopManualEnum::TYPE_DISCLOSURE) {
                continue;
            }
            $datumList[] = [
                'text' => $item['name'],
                'url'  => $item['url'],
            ];
        }
        return [
            'contract' => $contractInfo,
            'datum'    => $datumList,
        ];
    }


    /**
     * 获取支付记录
     *
     * @param $shopId
     * @return array
     * @throws Exception
     */
    public static function orderPayHistory($shopId): array
    {
        try {
            $openShopInfoObj = OpenShopMainProcessModel::query()
                                                       ->where("shopId", $shopId)
                                                       ->orderBy('id', 'desc')
                                                       ->with([
                                                           "signOrderRel" => function ($query) {
                                                               $query->with("payHistoryRel");
                                                           }
                                                       ])->first();


            return [
                "orderPayHistory" => OrderPayHistoryResource::collection(
                    $openShopInfoObj &&
                    $openShopInfoObj->signOrderRel &&
                    $openShopInfoObj->signOrderRel->payHistoryRel
                        ? $openShopInfoObj->signOrderRel->payHistoryRel->where('payStatus',
                        OpenShopSignOrderPayHistoryModel::PAY_STATUS_OK) : []
                )
            ];
        } catch (Exception $exception) {
            handleException($exception);
        }
    }

    /**
     * 待支付的订单列表
     * @param int $merchantUserId
     * @return array
     */
    public static function unpaidLists(int $merchantUserId): array
    {
        return OpenShopSignOrderModel::query()
                                     ->with('identityCardRel')
                                     ->where('merchantUserId', $merchantUserId)
                                     ->whereIn('step', [SignOrderEnum::STEP_2, SignOrderEnum::STEP_3])
                                     ->where('status', '>', SignOrderEnum::ORDER_STATUS_NO)
                                     ->limit(100)
                                     ->get()
                                     ->map(function ($item) {
                                         return [
                                             'shopName'      => SignOrderService::initShopName($item->identityCardRel->name),
                                             'orderNo'       => $item->orderNo,
                                             'secretOrderNo' => Reversible::encode($item->orderNo),
                                         ];
                                     })
                                     ->toArray();
    }
}
